###### @Author : WYK LastEditTime : 2021-10-01 09:42:40

######
#'@TODO: 
#'@param input: 
#'@param return_file_style: 
#'@param return_file: 
#': 
#'@author  *CY*
######
GEO_datapro <- function(dataset = NULL, soft = NULL, outputdir = NULL, cancer = NULL,
    num_of_gpl = 1) {
    if (!file.exists(outputdir)) {
        dir.create(outputdir, mode = "7777")
    }

    options(download.file.method.GEOquery = "libcurl")
    library(GEOquery)
    gse <- getGEO(GEO = dataset, destdir = outputdir, GSEMatrix = TRUE)
    geo_exp <- exprs(gse[[num_of_gpl]])
    geo_pdata <- pData(gse[[num_of_gpl]])
    probe <- getGEO(filename = paste0(outputdir, "/", soft, ".soft"))

    probe2id <- probe@dataTable@table[, c(1, which(grepl("Symbol", colnames(probe@dataTable@table),
        ignore.case = TRUE))[1])]
    probe2id <- probe2id[which(nchar(probe2id[, 2]) > 0), ]
    probe2id[, 3] <- unlist(lapply(probe2id[, 2], function(b) strsplit(b, split = " /// ")[[1]][1]))

    geo_exp <- geo_exp[which(rownames(geo_exp) %in% probe2id[, 1]), ]
    probe2id <- probe2id[match(rownames(geo_exp), probe2id[, 1]), ]
    geoexpr <- t(sapply(split(as.data.frame(geo_exp), probe2id[, 3]), function(x) colMeans(x[,
        1:ncol(x)])))

    geo_exp <- geoexpr
    geo_clin <- geo_pdata[match(colnames(geo_exp), rownames(geo_pdata)), ]
    save(geo_exp, geo_clin, file = paste0(outputdir, "./RData/", cancer, "_", dataset,
        "_", soft, "_", ".RData"))
    return(list(exp = geo_exp, clin = geo_clin))
}


# res -
# GEO_datapro(dataset='GSE37745',soft='GPL570',outputdir='DdatabaseGEO',cancer='NCSLC')

# GSE38832- GEO_datapro(dataset = 'GSE38832',soft ='GPL570' ,outputdir =
# '.GEO_colon',cancer = 'COAD')#

# 如果遇到报错，可以手动下载matrix文件与soft文件。
# 下载soft文件后，保留^PLATFORM=GPL13947开头行到!platform_table_end截止。


# a <- GEO_datapro(dataset = 'GSE73754', soft = 'GPL10558', outputdir = './',
# cancer = aa, num_of_gpl = 1)

# a




